package com.smzd.framework.core.actions;

import java.util.Map;

import org.springframework.validation.BindingResult;

import com.smzd.core.domain.IScopeOwnedEntity;
import com.smzd.core.domain.IntIdEntity;
import com.smzd.framework.utils.db.SORPage;

public abstract class AbstractOwnerScopedController<E extends IScopeOwnedEntity<S, O>, O extends IntIdEntity, S extends IntIdEntity>
        extends AbstractScopedController<E, S> {

    public String toAddPage(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initOwner(elem);
        return super.toAddPage(model, scopeId, elem, result);
    }

    public String postAddData(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initOwner(elem);
        return super.postAddData(model, scopeId, elem, result);
    }

    public String toListPage(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initOwner(elem);
        return super.toListPage(model, scopeId, elem, result);
    }

    public String getListData(Map<String, Object> model, int scopeId, SORPage<S, O, E> page, BindingResult result)
            throws Exception {
        if (page.getOwner() == null || page.getOwner().getId() == null) {
            page.setOwner(getOwner());
            System.out.println("--自动为获取列表数据装载了owner：" + page.getOwner());
        }
        return super.getListData(model, scopeId, page, result);
    }

    public String toEditPage(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initOwner(elem);
        return super.toEditPage(model, elem, result);
    }

    public String postEditData(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initOwner(elem);
        return super.postEditData(model, scopeId, elem, result);
    }

    public String postRemoveData(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initOwner(elem);
        return super.postRemoveData(model, scopeId, elem, result);
    }

    protected abstract O getOwner();

    protected void initOwner(E elem) {
        if (elem.getOwner() == null || elem.getOwner().getId() == null) {
            O owner = getOwner();
            elem.setOwner(owner);
        }
    }
}
